//
//  CommentInputView.m
//  IntelligenceCommunity
//
//  Created by zhangpei on 16/1/7.
//  Copyright © 2016年 zhangpei. All rights reserved.
//

#import "CommentInputView.h"
#import "InputTextView.h"
#import "UtilityConfig.h"
#import "ViewHelper.h"
#import "PublicMethod.h"
#import "Toast+UIView.h"

#define SEND_BUTTON_WIDTH 55.0f

#define INPUT_HEIGHT 42.0f

#define MAX_LINE 2


@interface CommentInputView ()
<UITextViewDelegate>
{
    UIWindow *window;
}

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) UIButton *sendButton;

@property (nonatomic, strong) InputTextView *inputTextView;

@property (nonatomic, strong) UIImageView *inputLine;


@property (assign, nonatomic) CGFloat previousTextViewContentHeight;


@end

static CommentInputView *commentInputView;

@implementation CommentInputView

@synthesize commentInputViewBlock;

@synthesize backgroundView, sendButton, inputTextView, inputLine,previousTextViewContentHeight;

+ (id)sharedCommentInputViewWithPlaceholder:(NSString *)placeholder withDropListViewBlock:(CommentInputViewBlock)block
{
    @synchronized (self)
    {
        //为了确保多线程情况下，仍然确保实体的唯一性
        if (commentInputView == nil)
        {
            commentInputView = [[CommentInputView alloc] init];
        }
        
        commentInputView.commentInputViewBlock = [block copy];
        
        commentInputView.inputTextView.text = nil;
        
        [commentInputView textViewDidChange:commentInputView.inputTextView];

        commentInputView.inputTextView.placeHolder = placeholder;
        
        [commentInputView.inputTextView becomeFirstResponder];
        
        commentInputView.hidden = NO;
        
        [WINDOW addSubview:commentInputView];

        return commentInputView;
    }
}


+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!commentInputView)
        {
            commentInputView = [super allocWithZone:zone]; //确保使用同一块内存地址
            return commentInputView;
        }
        return nil;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init
{
    self = [super init];
    
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        
        self.hidden = YES;
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleWillShowKeyboard:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleWillHideKeyboard:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
        
        [self initView];
    }
    return self;
}

- (void) initView
{
    window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    self.frame = window.bounds;
    [window addSubview:self];
    
    //透明覆层
    UIImageView *clearImageView = [[UIImageView alloc] initWithFrame:self.bounds];
    clearImageView.backgroundColor = [UIColor clearColor];
    [self addSubview:clearImageView];
    

    //
    backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - INPUT_HEIGHT, self.bounds.size.width, INPUT_HEIGHT)];
    backgroundView.backgroundColor = [UIColor whiteColor];
    backgroundView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);
    backgroundView.opaque = YES;
    
    
    [ViewHelper superView:backgroundView withFrame:CGRectMake(0, 0, backgroundView.bounds.size.width, 1) withImage:nil withBackgroundColor:COLORRGBA(204, 204, 204, 1) withUserInteractionEnabled:NO];

    
    
    CGFloat width = backgroundView.frame.size.width - SEND_BUTTON_WIDTH - 15 - 5;
    
    CGFloat height = [CommentInputView textViewLineHeight];
    
    self.previousTextViewContentHeight = height;
    
    inputTextView = [[InputTextView  alloc] initWithFrame:CGRectMake(5.0f, 3.0f, width, height)];
    inputTextView.delegate = self;
    inputTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    inputTextView.backgroundColor = [UIColor clearColor];
    [backgroundView addSubview:inputTextView];
    
    inputLine = [ViewHelper superView:backgroundView withFrame:CGRectMake(inputTextView.frame.origin.x + 3, backgroundView.frame.size.height - 5, inputTextView.bounds.size.width - 6, 1.5) withImage:nil withBackgroundColor:COLORRGBA(73, 150, 253, 1) withUserInteractionEnabled:NO];
    
    sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    sendButton.frame = CGRectMake(backgroundView.bounds.size.width - SEND_BUTTON_WIDTH - 7.5, backgroundView.frame.size.height - 35, SEND_BUTTON_WIDTH, 30);
    [sendButton setTitle:@"确定" forState:UIControlStateNormal];
    
    [sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    sendButton.backgroundColor = COLORRGBA(73, 150, 253, 1);
    
    sendButton.layer.cornerRadius = 5;
    
    sendButton.clipsToBounds = YES;
    
    [sendButton addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [backgroundView addSubview:sendButton];
    
    [self addSubview:backgroundView];
}


- (void)buttonClick
{
    //点击确定
    NSString *sendText = inputTextView.text;
    
    if ([PublicMethod checkStrings:sendText])
    {
        [inputTextView resignFirstResponder];
        
        self.hidden = YES;
        
        if (commentInputViewBlock)
        {
            commentInputViewBlock(sendText);
        }
    }
    else
    {
        [WINDOW makeToast:@"不能发布空白内容" duration:1.5f position:@"center"];
    }
}


+ (CGFloat)textViewLineHeight
{
    return 36.0f; // for fontSize 16.0f
}

+ (CGFloat)maxLines
{
    return MAX_LINE;
}

+ (CGFloat)maxHeight
{
    return ([CommentInputView maxLines] + 1.0f) * [CommentInputView textViewLineHeight];
}

#pragma mark - Message input view
- (void)adjustTextViewHeightBy:(CGFloat)changeInHeight
{
    CGRect prevFrame = inputTextView.frame;
    
    NSUInteger numLines = MAX([inputTextView numberOfLinesOfText],[inputTextView.text componentsSeparatedByString:@"\n"].count + 1);
    
    inputTextView.frame = CGRectMake(prevFrame.origin.x,
                                     prevFrame.origin.y,
                                     prevFrame.size.width,
                                     prevFrame.size.height + changeInHeight);
    
    inputTextView.contentInset = UIEdgeInsetsMake((numLines >= 6 ? 4.0f : 0.0f),
                                                  0.0f,
                                                  (numLines >= 6 ? 4.0f : 0.0f),
                                                  0.0f);
    
    inputTextView.scrollEnabled = (numLines >= MAX_LINE);
    
    if(numLines >= MAX_LINE)
    {
        CGPoint bottomOffset = CGPointMake(0.0f, inputTextView.contentSize.height - inputTextView.bounds.size.height);
        
        [inputTextView setContentOffset:bottomOffset animated:YES];
    }
}



#pragma mark - Text view delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [textView becomeFirstResponder];
    
    if(!self.previousTextViewContentHeight)
        self.previousTextViewContentHeight = textView.contentSize.height;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat maxHeight = [CommentInputView maxHeight];
    
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, maxHeight)];
    
    CGFloat textViewContentHeight = size.height;
    
    // End of textView.contentSize replacement code
    
    BOOL isShrinking = textViewContentHeight < self.previousTextViewContentHeight;
    
    CGFloat changeInHeight = textViewContentHeight - self.previousTextViewContentHeight;
    
    if(!isShrinking && self.previousTextViewContentHeight == maxHeight)
    {
        changeInHeight = 0;
    }
    else
    {
        changeInHeight = MIN(changeInHeight, maxHeight - self.previousTextViewContentHeight);
    }
    
    if(changeInHeight != 0.0f) {
        //        if(!isShrinking)
        //            [self.inputToolBarView adjustTextViewHeightBy:changeInHeight];
        
        [UIView animateWithDuration:0.25f
                         animations:^{
                            
                             if(isShrinking) {
                                 // if shrinking the view, animate text view frame BEFORE input view frame
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                             
                             CGRect inputViewFrame = backgroundView.frame;
                             backgroundView.frame = CGRectMake(0.0f,
                                                                      inputViewFrame.origin.y - changeInHeight,
                                                                      inputViewFrame.size.width,
                                                                      inputViewFrame.size.height + changeInHeight);
                             
                             sendButton.frame = CGRectMake(backgroundView.bounds.size.width - SEND_BUTTON_WIDTH - 7.5, backgroundView.frame.size.height - 35, SEND_BUTTON_WIDTH, 30);
                             
                             inputLine.frame = CGRectMake(inputTextView.frame.origin.x + 3, backgroundView.frame.size.height - 5, inputTextView.bounds.size.width - 6, 1.5);
                             
                             if(!isShrinking) {
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                         }
                         completion:^(BOOL finished) {
                         }];
        
        
        self.previousTextViewContentHeight = MIN(textViewContentHeight, maxHeight);
    }
    
    sendButton.enabled = ([textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length > 0);
}


#pragma mark - Keyboard notifications

- (void)handleWillShowKeyboard:(NSNotification *)notification
{
    CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration
                          delay:0.0f
                        options:[CommentInputView animationOptionsForCurve:curve]
                     animations:^{
                         
                         CGRect inputViewFrame = backgroundView.frame;
                         
                         CGFloat inputViewFrameY = self.bounds.size.height - inputViewFrame.size.height - keyboardRect.size.height;
                         
                         backgroundView.frame = CGRectMake(inputViewFrame.origin.x,
                                                           inputViewFrameY,
                                                           inputViewFrame.size.width,
                                                           inputViewFrame.size.height);
                         
                         
                     }
                     completion:^(BOOL finished) {
                     }];

}

- (void)handleWillHideKeyboard:(NSNotification *)notification
{
    inputTextView.text = nil;
    
    [self textViewDidChange:inputTextView];
    
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration
                          delay:0.0f
                        options:[CommentInputView animationOptionsForCurve:curve]
                     animations:^{
                         
                         backgroundView.frame = CGRectMake(0, self.bounds.size.height - backgroundView.bounds.size.height, self.bounds.size.width, backgroundView.bounds.size.height);
                     }
                     completion:^(BOOL finished) {
                     }];
}

+ (UIViewAnimationOptions)animationOptionsForCurve:(UIViewAnimationCurve)curve
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
            break;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
            break;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
            break;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
            break;
    }
    
    return kNilOptions;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [inputTextView resignFirstResponder];
    self.hidden = YES;
}

@end
